package com.iot.lemon.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;

import com.alibaba.dubbo.config.annotation.Service;
import com.iot.lemon.mapper.TTenementMapper;
import com.iot.lemon.model.TArea;
import com.iot.lemon.model.TBuilding;
import com.iot.lemon.model.TCar;
import com.iot.lemon.model.THouse;
import com.iot.lemon.model.TTenement;
import com.iot.lemon.service.TAreaService;
import com.iot.lemon.service.TBuildingService;
import com.iot.lemon.service.TCarService;
import com.iot.lemon.service.THouseService;
import com.iot.lemon.service.TTenementService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;

/**
 * <p>
 * 住户 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-08-18
 */
@Service(interfaceClass = TTenementService.class)
@CacheConfig(cacheNames = "TTenement")
public class TTenementServiceImpl extends BaseServiceImpl<TTenement, TTenementMapper> implements TTenementService {
    @Autowired
    private TAreaService areaService;
    @Autowired
    private TBuildingService buildingService;
    @Autowired
    private THouseService houseService;
    @Autowired
    private TCarService carService;

    @Override
    public Pagination<TTenement> query(Map<String, Object> params) {
        Pagination<TTenement> page = super.query(params);
        for (TTenement tenement : page.getRecords()) {
            THouse house = houseService.queryById(tenement.getHouseId());
            if (house != null) {
                TBuilding building = buildingService.queryById(house.getBuildingId());
                if (building != null) {
                    TArea area = areaService.queryById(building.getAreaId());
                    if (area != null) {
                        tenement.setHouseName(
                            area.getAreaName() + "-" + building.getBuildingName() + "-" + house.getHouseNo());
                    } else {
                        tenement.setHouseName(building.getBuildingName() + "-" + house.getHouseNo());
                    }
                } else {
                    tenement.setHouseName(house.getHouseNo());
                }
                tenement.setCarQuantity(carService.count(new TCar().setHouseId(house.getId())));
            }
        }
        return page;
    }

    @Override
    public TTenement queryById(Long id) {
        TTenement tenement = super.queryById(id);
        THouse house = houseService.queryById(tenement.getHouseId());
        if (house != null) {
            tenement.setBuildingId(house.getBuildingId());
            TBuilding building = buildingService.queryById(house.getBuildingId());
            if (building != null) {
                tenement.setAreaId(building.getAreaId());
            }
        }
        return tenement;
    }
}
